<template>
  <div class="main-container">
    <div class="header">
      <div style="display: flex; align-items: center;">
        <el-icon size="24" style="margin-right: 10px;"><Monitor /></el-icon>
        <h2>设备管理系统</h2>
      </div>
      <div style="display: flex; align-items: center;">
        <span style="margin-right: 15px;">欢迎，{{ username }}</span>
        <el-button type="text" @click="handleLogout" style="color: white;">
          <el-icon><SwitchButton /></el-icon>
          退出登录
        </el-button>
      </div>
    </div>
    
    <div class="content">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h3>{{ isEdit ? '编辑分设备' : '添加分设备' }}</h3>
        <el-button @click="handleBack">
          <el-icon><ArrowLeft /></el-icon>
          返回列表
        </el-button>
      </div>
      
      <el-card style="max-width: 600px; margin: 0 auto;">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="150px">
          <el-form-item label="分设备ID" prop="subDeviceId">
            <el-input v-model="form.subDeviceId" placeholder="请输入分设备ID" />
          </el-form-item>
          
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
          </el-form-item>
          
          <el-form-item label="设备型号" prop="deviceModel">
            <el-select v-model="form.deviceModel" placeholder="请选择设备型号" style="width: 100%;">
              <el-option label="RS485" value="RS485" />
              <el-option label="RS232" value="RS232" />
              <el-option label="Modbus TCP" value="Modbus TCP" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="轮询应答超时时间" prop="responseTimeout">
            <el-input-number 
              v-model="form.responseTimeout" 
              :min="100" 
              :max="10000" 
              :step="100"
              style="width: 100%;"
            />
            <span style="margin-left: 10px; color: #999;">毫秒</span>
          </el-form-item>
          
          <el-form-item label="轮询周期时间" prop="pollingInterval">
            <el-input-number 
              v-model="form.pollingInterval" 
              :min="1000" 
              :max="60000" 
              :step="1000"
              style="width: 100%;"
            />
            <span style="margin-left: 10px; color: #999;">毫秒</span>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSubmit" :loading="loading">
              {{ isEdit ? '更新' : '创建' }}
            </el-button>
            <el-button @click="handleReset">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'SubDeviceForm',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const loading = ref(false)
    const username = ref(sessionStorage.getItem('username') || '')
    const formRef = ref()
    const isEdit = ref(!!route.params.id)
    const mainImei = ref(route.params.mainImei)

    const form = reactive({
      subDeviceId: '',
      deviceName: '',
      deviceModel: '',
      responseTimeout: 500,
      pollingInterval: 5000,
      mainDeviceImei: mainImei.value
    })

    const rules = reactive({
      subDeviceId: [
        { required: true, message: '请输入分设备ID', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
      ],
      deviceName: [
        { required: true, message: '请输入设备名称', trigger: 'blur' },
        { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
      ],
      deviceModel: [
        { required: true, message: '请选择设备型号', trigger: 'change' }
      ],
      responseTimeout: [
        { required: true, message: '请输入轮询应答超时时间', trigger: 'blur' },
        { type: 'number', min: 100, max: 10000, message: '超时时间应在100-10000毫秒之间', trigger: 'blur' }
      ],
      pollingInterval: [
        { required: true, message: '请输入轮询周期时间', trigger: 'blur' },
        { type: 'number', min: 1000, max: 60000, message: '轮询周期应在1000-60000毫秒之间', trigger: 'blur' }
      ]
    })

    const loadSubDevice = async () => {
      if (!isEdit.value) return
      
      try {
        loading.value = true
        const token = sessionStorage.getItem('token')
        const response = await axios.get(`/api/sub-devices/${route.params.id}`, {
          headers: { Authorization: `Bearer ${token}` }
        })
        
        if (response.data.success) {
          Object.assign(form, response.data.data)
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('加载分设备信息失败')
      } finally {
        loading.value = false
      }
    }

    const handleSubmit = async () => {
      try {
        await formRef.value.validate()
        loading.value = true
        
        const token = sessionStorage.getItem('token')
        const headers = { Authorization: `Bearer ${token}` }
        
        let response
        if (isEdit.value) {
          response = await axios.put(`/api/sub-devices/${route.params.id}`, form, { headers })
        } else {
          response = await axios.post('/api/sub-devices', form, { headers })
        }
        
        if (response.data.success) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          handleBack()
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        if (error.response?.data?.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
        }
      } finally {
        loading.value = false
      }
    }

    const handleReset = () => {
      formRef.value.resetFields()
    }

    const handleBack = () => {
      if (isEdit.value) {
        // 从编辑页面返回，需要获取主设备IMEI
        router.push(`/devices/config/${form.mainDeviceImei}`)
      } else {
        router.push(`/devices/config/${mainImei.value}`)
      }
    }

    const handleLogout = () => {
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('username')
      router.push('/login')
    }

    onMounted(() => {
      if (isEdit.value) {
        loadSubDevice()
      }
    })

    return {
      loading,
      username,
      formRef,
      isEdit,
      form,
      rules,
      handleSubmit,
      handleReset,
      handleBack,
      handleLogout
    }
  }
}
</script>

<style scoped>
.main-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.content {
  padding: 30px;
}

.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
</style>